package com.hc.conferencecheck.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hc.conferencecheck.entity.AttendRecord;
import com.hc.conferencecheck.entity.AttendRecordExample;
import com.hc.conferencecheck.entity.ResultMsg;
import com.hc.conferencecheck.entity.ResultStatusCode;
import com.hc.conferencecheck.entity.entityDTO.AttendRecordDTO;
import com.hc.conferencecheck.entity.entityDTO.AttendRecordDTOForExport;
import com.hc.conferencecheck.entity.entityDTO.ConferenceDetailDTO;
import com.hc.conferencecheck.entity.entityDTO.ConventionerAttendRecord;
import com.hc.conferencecheck.mapper.AttendRecordMapper;
import com.hc.conferencecheck.mapper.ConventionerMapper;
import com.hc.conferencecheck.service.AttendRecordService;
import com.hc.conferencecheck.service.MessageService;
import com.hc.conferencecheck.utils.PageHelperUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会议申请记录service实现类
 */
//开启事务管理
@Transactional
@Service
public class AttendRecordServiceImpl implements AttendRecordService {
    public static final Logger logger = LoggerFactory.getLogger(AttendRecordServiceImpl.class);
    @Resource
    private AttendRecordMapper attendRecordMapper;
    @Resource
    private ConventionerMapper conventionerMapper;
    @Resource
    private MessageService messageServiceImpl;

    /**
     * 用于会议审核页面会议申请记录导出的查询方法
     *
     * @param params
     * @return
     */
    public List<AttendRecordDTOForExport> selectAttendRecordInfoByConferenceId(Map<String, Object> params) {
        List<AttendRecordDTOForExport> attendRecordDTOForExports = attendRecordMapper.selectAttendRecordInfoByConferenceId(params);
        return attendRecordDTOForExports;
    }


    /**
     * 审核页面查询所有的未通过申请记录（未通过，审核中）
     */
    public ResultMsg selectAllAttendRecordUnApproved(Map<String, Object> params) {
        //获取分页参数
        //获取当前页数
        Object pageNumberObj = params.get("pageNumber");
        int pageNumber = Integer.parseInt(pageNumberObj.toString());
        //默认20页
        PageHelper.startPage(pageNumber, 20);
        List<AttendRecordDTO> attendRecordDTOS = attendRecordMapper.selectAllAttendRecordUnApproved();
        //获取总记录数
        if (attendRecordDTOS != null && attendRecordDTOS.size() > 0) {
            //获取总条数
            PageInfo<AttendRecordDTO> pageinfo = new PageInfo<>(attendRecordDTOS);
            long pageTotal = pageinfo.getTotal();
            // 用总条数获取总页数
            pageTotal = (pageTotal + 20 - 1) / 20;

            Map<String, Object> result = new HashMap<>();
            result.put("dataList", attendRecordDTOS);
            result.put("pageTotal", pageTotal);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "没有申请记录信息");
        }
    }

    /**
     * 根据会议ID和用户ID查询申请记录
     */
    public List<ConferenceDetailDTO> selectAttendRecordByIds(Map<String, Object> params) {
        List<ConferenceDetailDTO> conferenceDetailDTOS = attendRecordMapper.selectAttendRecordByIds(params);
        return conferenceDetailDTOS;
    }


    /**
     * 更改会议申请记录的审核状态
     */
    public ResultMsg editIsApproved(Map<String, Object> params) {
        //获取会议申请记录ID
        Object attendRecordIdObj = params.get("attendRecordId");
        if (attendRecordIdObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议申请记录ID不可为空");
        }
        int attendRecordId = Integer.parseInt(attendRecordIdObj.toString());
        //获取状态码
        Object statusCodeObj = params.get("statusCode");
        if (statusCodeObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "状态码不可为空");
        }
        int statusCode = Integer.parseInt(statusCodeObj.toString());


        //更新操作
        //根据ID更新指定会议申请记录的审核状态；
        AttendRecord attendRecord = new AttendRecord();
        attendRecord.setId(attendRecordId);
        attendRecord.setIsApproved((byte) statusCode);
        attendRecord.setApprovedTime(new Date());
        String reason = "";
        Object reasonObj = params.get("remark");
        if (reasonObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "未通过原因不可为空");
        }
        reason = reasonObj.toString();
        attendRecord.setReason(reason);

        int i = attendRecordMapper.updateByPrimaryKeySelective(attendRecord);
        if (i == 1) {
            //无论是否通过都要发送短信
            Map<String, Object> param = new HashMap<>();
            param.put("name", params.get("name").toString());
            String statusstr = "";
            switch (statusCode) {
                case 0:
                    statusstr = "未通过";
                    break;
                case 1:
                    statusstr = "已通过";
                    break;
            }
            param.put("status", statusstr);
            param.put("remark", reason);
            String jsonString = JSONObject.toJSONString(param);
            String status002 = messageServiceImpl.sendApprovedMessage02(attendRecordId, jsonString);
            logger.info(status002);
            if ("OK".equals(status002)) {
                return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "修改成功");
            } else {
                logger.error("修改成功,但是短信发送失败");
                return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "修改成功,但是短信发送失败");
            }
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "修改失败");
        }
    }

    /**
     * 查询所有的会议申请记录,所有已通过，或者未通过，或者所有的会议申请记录
     */
    public ResultMsg selectAllAttendRecordIsApproved(Map<String, Object> params) {
        Object statusCodeObj = params.get("statusCode");
        if (statusCodeObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "状态码不可为空");
        }
        int statusCode = Integer.parseInt(statusCodeObj.toString());

        AttendRecordExample example = new AttendRecordExample();
        AttendRecordExample.Criteria criteria = example.createCriteria();
        //根据状态码，查询符合条件的会议申请记录
        if (statusCode == 0) {
            //查询所有未通过申请记录
            criteria.andIsApprovedEqualTo((byte) 0);
        } else if (statusCode == 1) {
            //查询所有已通过申请记录
            criteria.andIsApprovedEqualTo((byte) 1);
        } else {
            //查询所有申请记录
            criteria.andIdIsNotNull();
        }

        //处理分页参数
        PageHelperUtils.startPage(params);

        //执行查询
        List<AttendRecord> attendRecords = attendRecordMapper.selectByExample(example);
        //获取总记录数
        PageInfo<AttendRecord> pageInfo = new PageInfo<>(attendRecords);
        long pageTotal = pageInfo.getTotal();

        //返回结果集
        Map<String, Object> result = new HashMap<>();
        result.put("dataList", attendRecords);
        result.put("pageTotal", pageTotal);
        return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
    }

    /**
     * 查询用户所有会议申请记录
     */
    public ResultMsg selectConventionerAttendRecord(Map<String, Object> params) {
        //处理分页参数
//        PageHelperUtils.startPage(params);
        List<ConventionerAttendRecord> conventionerAttendRecords = attendRecordMapper.selectConventionerAttendRecord(params);


        if (conventionerAttendRecords != null && conventionerAttendRecords.size() > 0) {
            //获取总记录数
            PageInfo<ConventionerAttendRecord> pageInfo = new PageInfo<>(conventionerAttendRecords);
            long pageTotal = pageInfo.getTotal();

            //返回结果集
            Map<String, Object> result = new HashMap<>();
            result.put("dataList", conventionerAttendRecords);
            result.put("pageTotal", pageTotal);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "无会议记录");
        }
    }

    /**
     * 更改会议申请记录的签到状态
     */
    public ResultMsg editSignCode(Map<String, Object> params) {
        //获取会议申请记录ID
        Object attendRecordIdObj = params.get("attendRecordId");
        if (attendRecordIdObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议申请记录ID不可为空");
        }
        int attendRecordId = Integer.parseInt(attendRecordIdObj.toString());
        //获取签到状态码
        Object signCodeObj = params.get("signCode");
        if (signCodeObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议签到状态码不可为空");
        }
        int signCode = Integer.parseInt(signCodeObj.toString());

        //根据ID更新指定会议申请记录的签到状态；
        AttendRecord attendRecord = new AttendRecord();
        attendRecord.setId(attendRecordId);
        attendRecord.setIsSign((byte) signCode);
        attendRecord.setSignInTime(new Date());

        int i = attendRecordMapper.updateByPrimaryKeySelective(attendRecord);
        if (i == 1) {
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), "修改成功");
        } else {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "修改失败");
        }
    }

    /**
     * 根据会议申请记录ID，查询会议申请记录
     */
    public ResultMsg selectAttendRecordByPrimaryKey(Map<String, Object> params) {
        //获取会议申请记录ID
        Object attendRecordIdObj = params.get("attendRecordId");
        if (attendRecordIdObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "会议申请记录ID不可为空");
        }
        int attendRecordId = Integer.parseInt(attendRecordIdObj.toString());

        //根据主键查询会议申请记录
        AttendRecord attendRecord = attendRecordMapper.selectByPrimaryKey(attendRecordId);
        if (attendRecord == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "未找到指定会议申请记录");
        }

        //返回结果集
        Map<String, Object> data = new HashMap<>();
        data.put("dataList", attendRecord);
        return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), data);
    }

    /**
     * 查询某用户某种状态的申请记录(通过或者未通过的申请记录)
     */
    public ResultMsg selectConferencesByConventionerId(Map<String, Object> params) {
        //处理分页参数
        PageHelperUtils.startPage(params);

        //获取用户ID
        Object conventionerIdObj = params.get("conventionerId");
        if (conventionerIdObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "申请者ID不可为空");
        }
        int conventionerId = Integer.parseInt(conventionerIdObj.toString());
        //获取查询会议的状态码0-审核未通过；1-审核已通过；
        Object statusCodeObj = params.get("statusCode");
        if (statusCodeObj == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "状态码不可为空");
        }
        int statusCode = Integer.parseInt(statusCodeObj.toString());
        //根据用户ID和状态码获取用户指定状态的申请记录
        List<AttendRecord> attendRecords = selectAttendRecordByStatusCode(conventionerId, statusCode);

        if (attendRecords == null) {
            return new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "当前用户没有申请记录");
        } else {
            //获取总记录数
            PageInfo<AttendRecord> pageInfo = new PageInfo<>(attendRecords);
            long pageTotal = pageInfo.getTotal();

            Map<String, Object> result = new HashMap<>();
            result.put("dataList", attendRecords);
            result.put("pageTotal", pageTotal);
            return new ResultMsg(ResultStatusCode.OK.getCode(), ResultStatusCode.OK.getMsg(), result);
        }
    }

    /**
     * 查询用户指定状态的申请记录
     */
    public List<AttendRecord> selectAttendRecordByStatusCode(int conventionerId, int statusCode) {
        AttendRecordExample example = new AttendRecordExample();
        AttendRecordExample.Criteria criteria = example.createCriteria();
        criteria.andConventionerIdEqualTo(conventionerId);
        criteria.andIsApprovedEqualTo((byte) statusCode);

        List<AttendRecord> attendRecords = attendRecordMapper.selectByExample(example);
        if (attendRecords != null && attendRecords.size() > 0) {
            return attendRecords;
        } else {
            return null;
        }
    }

    /**
     * 根据用户ID和会议ID的，查询指定会议记录
     */
    public AttendRecord selectAttendRecordByDoubleId(int conventionerId, int conferenceId) {
        AttendRecordExample example = new AttendRecordExample();
        AttendRecordExample.Criteria criteria = example.createCriteria();
        criteria.andConventionerIdEqualTo(conventionerId);
        criteria.andConferenceIdEqualTo(conferenceId);

        List<AttendRecord> attendRecords = attendRecordMapper.selectByExample(example);
        if (attendRecords != null && attendRecords.size() > 0) {
            return attendRecords.get(0);
        } else {
            return null;
        }
    }
}
